package calao;

import java.util.HashMap;

public abstract class Properties
{

	static final String APPLICATIONS = "applications";
	static final String LANGUAGE = "lang";
	static final String DESKTOP_FEATURES = "desktop.features";
	static final String DESKTOP_SHORTCUTS = "desktop.shortcuts";
	static final String DESKTOP_TITLE = "desktop.title";
	
	private static final String LIST_SEPARATOR = ",";
	
	final Properties parent;
	final HashMap<String,String> map;
	
	Properties(Properties parent)
	{
		this(parent, null);
	}
		
	Properties(Properties parent, HashMap<String,String> map)
	{
		this.parent = parent;
		this.map = map!=null? map : new HashMap<String,String>();
	}

	synchronized public void setProperty(String name, String value)
	{
		map.put(name, value);
	}

	public abstract void save();

	synchronized public final String getProperty(String name) {
		String value = map.get(name);
		if (value==null && parent!=null) return parent.getProperty(name);
		return value;
	}
	
	public final int getIntProperty(String name, int defaultValue) {
		String value = getProperty(name);
		return value!=null? Integer.parseInt(value) : defaultValue;
	}
	
	public final int getIntProperty(String name) {
		return getIntProperty(name, 0);
	}

	public final void setIntProperty(String name, int value) {
		setProperty(name, Integer.toString(value));
	}

	public final String[] getStringListProperty(String name) {
		String value = getProperty(name);
		return value==null || value.length()==0? 
				new String[0] : value.split(LIST_SEPARATOR); 
	}
	
	public final int[] getIntListProperty(String name) {
		String[] values = getStringListProperty(name);
		int[] result = new int[values.length];
		for (int i=0; i<result.length; i++) result[i] = Integer.parseInt(values[i]);
		return result;
	}
	
	public final void setIntListProperty(String name, int[] list)
	{
		StringBuffer value = new StringBuffer();
		for (int lval : list) {
			if (value.length()>0) value.append(LIST_SEPARATOR);
			value.append(lval);
		}
		setProperty(name, value.toString());		
	}

	public final void setStringListProperty(String name, String[] list)
	{
		StringBuffer value = new StringBuffer();
		for (String lval : list) {
			if (value.length()>0) value.append(LIST_SEPARATOR);
			value.append(lval);
		}
		setProperty(name, value.toString());
	}
	
	synchronized public String[] getNamesStartingWith(String prefix)
	{
		String[] result = new String[map.size()];
		int count = 0;
		for (String name : map.keySet()) {
			if (name.startsWith(prefix)) result[count++] = name;
		}
		return java.util.Arrays.copyOf(result, count);
	}

}
